﻿namespace dotnet_notes.Controllers
{
    /// <summary>
    /// 品牌管理
    /// </summary>
    public class BrandController(SqlSugarClient db, IMapper mapper) : BusinessBaseController(db, mapper)
    {
        /// <summary>
        /// 审核列表
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> ExamineList(ListReq<Sys_BrandQueryReq> req)
        {
            var list = await Db.Queryable<Sys_Brand_Examine>()
                .Where(it => req.Body.ExamineStatusArray.Contains(it.ExamineStatus))
                .WhereIF(req.Body.Name.HasValue(), it => it.Name.Contains(req.Body.Name.Trim()))
                .OrderBy(it => it.ID, OrderByType.Desc)
                .GetPageListAsync(req.PageNumber, req.PageSize);

            return Ok(list);
        }

        /// <summary>
        /// 列表
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> List(ListReq<Sys_BrandQueryReq> req)
        {
            var list = await Db.Queryable<Sys_Brand>()
                .WhereIF(req.Body.Name.HasValue(), it => it.Name.Contains(req.Body.Name.Trim()))
                .OrderBy(it => it.ID, OrderByType.Desc)
                .GetPageListAsync(req.PageNumber, req.PageSize);

            return Ok(list);
        }

        /// <summary>
        /// 审核历史列表
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> ExamineHistoryList(CommonPrimaryKeyReq req)
        {
            var list = await Db.Queryable<Sys_Brand_Examine>()
                .Where(it => it.BusinessID == req.ID)
                .OrderBy(it => it.SubmitTime)
                .ToListAsync();

            return Ok(list.ToExamineHistoryList());
        }

        /// <summary>
        /// 添加
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Add(Sys_BrandAddReq req)
        {
            // 检查是否有未处理的申请
            await Db.Queryable<Sys_Brand_Examine>().CheckExistsAsync(
                it => it.Name == req.Name && it.ExamineStatus == ExamineStatusEnum.PendingApproval,
                MessageConfig.PendingApproval);

            // 名称重复检查
            await Db.Queryable<Sys_Brand>().CheckExistsAsync(it => it.Name == req.Name);

            var examine = Mapper.Map<Sys_Brand_Examine>(req);

            int id = await Db.Insertable(examine).ExecuteReturnIdentityAsync();
            return Ok(id);
        }

        /// <summary>
        /// 审核修改
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> ExamineModify(Sys_BrandModifyReq req)
        {
            var examine = await Db.Queryable<Sys_Brand_Examine>().GetFirstAsync(it => it.ID == req.ID);

            switch (examine.ExamineType)
            {
                case ExamineTypeEnum.Add:

                    // 名称重复检查
                    await Db.Queryable<Sys_Brand>().CheckExistsAsync(it => it.Name == req.Name);
                    break;

                case ExamineTypeEnum.Modify:

                    // 名称重复检查(排除当前记录)
                    await Db.Queryable<Sys_Brand>().CheckExistsAsync(it =>
                        it.Name == req.Name && it.ID != examine.BusinessID);
                    break;

                default: break;
            }

            Mapper.Map(req, examine);

            await Db.Updateable(examine).ExecuteCommandAsync();
            return Ok();
        }

        /// <summary>
        /// 修改
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Modify(Sys_BrandModifyReq req)
        {
            // 检查是否有未处理的申请
            await Db.Queryable<Sys_Brand_Examine>().CheckExistsAsync(
                it => it.BusinessID == req.ID && it.ExamineStatus == ExamineStatusEnum.PendingApproval,
                MessageConfig.PendingApproval);

            // 记录存在检查
            await Db.Queryable<Sys_Brand>().GetFirstAsync(it => it.ID == req.ID);

            // 名称重复检查(排除当前记录)
            await Db.Queryable<Sys_Brand>().CheckExistsAsync(it => it.Name == req.Name && it.ID != req.ID);

            var examine = Mapper.Map<Sys_Brand_Examine>(req);
            examine.BusinessID = req.ID;
            examine.ExamineType = ExamineTypeEnum.Modify;

            int id = await Db.Insertable(examine).ExecuteReturnIdentityAsync();
            return Ok(id);
        }

        /// <summary>
        /// 删除
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Delete(CommonPrimaryKeyReq req)
        {
            var brand = await Db.Queryable<Sys_Brand>().GetFirstAsync(it => it.ID == req.ID);

            // 检查是否有未处理的申请
            await Db.Queryable<Sys_Brand_Examine>().CheckExistsAsync(
                it => it.BusinessID == brand.ID && it.ExamineStatus == ExamineStatusEnum.PendingApproval,
                MessageConfig.PendingApproval);

            var examine = Mapper.Map<Sys_Brand_Examine>(brand);
            examine.ExamineType = ExamineTypeEnum.Delete;

            int id = await Db.Insertable(examine).ExecuteReturnIdentityAsync();
            return Ok(id);
        }

        /// <summary>
        /// 恢复
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Recover(CommonPrimaryKeyReq req)
        {
            var brand = await Db.Queryable<Sys_Brand>().GetFirstAsync(it => it.ID == req.ID);

            // 检查是否有未处理的申请
            await Db.Queryable<Sys_Brand_Examine>().CheckExistsAsync(
                it => it.BusinessID == brand.ID && it.ExamineStatus == ExamineStatusEnum.PendingApproval,
                MessageConfig.PendingApproval);

            var examine = Mapper.Map<Sys_Brand_Examine>(brand);
            examine.ExamineType = ExamineTypeEnum.Recover;

            int id = await Db.Insertable(examine).ExecuteReturnIdentityAsync();
            return Ok(id);
        }

        /// <summary>
        /// 审核
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Examine(CommonExamineReq req)
        {
            var examine = await Db.Queryable<Sys_Brand_Examine>().GetFirstAsync(it => it.ID == req.ID);
            if (examine.ExamineStatus != ExamineStatusEnum.PendingApproval)
            {
                throw new InvalidOperationException(MessageConfig.InvalidStatus);
            }

            examine.ExamineTime = DateTime.Now;
            examine.ExamineRemark = req.ExamineRemark;

            if (req.ExamineResult == ExamineResultEnum.Approved)
            {
                examine.ExamineStatus = ExamineStatusEnum.Approved;

                // 获取策略
                var strategy = BrandExamineStrategyFactory.GetStrategy(examine.ExamineType);

                // 执行策略
                await strategy.Execute(Db, Mapper, examine);
            }
            else
            {
                using var tran = Db.UseTran();

                examine.ExamineStatus = ExamineStatusEnum.Rejected;
                await Db.Updateable(examine).ExecuteCommandAsync();

                Mapper.Map(examine, examine);
                examine.ExamineTime = null;

                // 新增一条审核记录, 目的是保留驳回的历史, 重新提交基于这条新的审核记录
                int id = await Db.Insertable(examine).ExecuteReturnIdentityAsync();

                await Db.CommitTranAsync();
                return Ok(id);
            }

            return Ok(examine.BusinessID);
        }
    }
}
